# Simple PowerShell script to check IP availability

# File paths
$excelFile = "c:\Users\Administrator\Desktop\ip_pool\ip_detail.xlsx"
$outputFile = "c:\Users\Administrator\Desktop\ip_pool\available_ips.csv"

Write-Host "Starting IP check"
Write-Host "Input file: $excelFile"

# Check if file exists
if (-not (Test-Path $excelFile)) {
    Write-Host "Error: Input file not found"
    exit 1
}

# Try to read Excel file using built-in methods
# Since Import-Excel might have issues, we'll use COM object
try {
    # Create Excel COM object
    $excel = New-Object -ComObject Excel.Application
    $excel.Visible = $false
    $excel.DisplayAlerts = $false
    
    # Open workbook
    Write-Host "Reading Excel file..."
    $workbook = $excel.Workbooks.Open($excelFile)
    $sheet = $workbook.ActiveSheet
    
    # Get total rows
    $totalRows = $sheet.UsedRange.Rows.Count
    Write-Host "Total rows: $totalRows"
    
    # Extract IPs from first column
    $ipList = @()
    for ($row = 2; $row -le $totalRows; $row++) {
        $cellValue = $sheet.Cells.Item($row, 1).Text
        if ($cellValue -ne "") {
            $ipList += $cellValue.Trim()
        }
    }
    
    # Clean up Excel
    $workbook.Close()
    $excel.Quit()
    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($sheet) | Out-Null
    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook) | Out-Null
    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel) | Out-Null
    [System.GC]::Collect()
    
    Write-Host "Extracted $($ipList.Count) IP addresses"
    
    # Check each IP
    $availableIPs = @()
    $total = $ipList.Count
    
    foreach ($ip in $ipList) {
        Write-Host "Checking IP: $ip"
        
        # Validate IP format
        if ($ip -notmatch '^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$') {
            Write-Host "  Invalid IP format, skipping"
            continue
        }
        
        $isAvailable = $false
        
        try {
            # Create web client with proxy
            $proxy = New-Object System.Net.WebProxy -ArgumentList "http://$ip"
            $client = New-Object System.Net.WebClient
            $client.Proxy = $proxy
            $client.Headers.Add("User-Agent", "Mozilla/5.0")
            $client.Timeout = 5000
            
            # Try to access Baidu
            $response = $client.DownloadString("https://www.baidu.com")
            
            if ($response -ne $null -and $response.Length -gt 0) {
                Write-Host "  IP is available"
                $availableIPs += $ip
            }
        } catch {
            Write-Host "  IP is not available: $($_.Exception.Message)"
        }
    }
    
    # Save available IPs
    Write-Host "\nCheck completed!"
    Write-Host "Available IPs: $($availableIPs.Count)"
    
    if ($availableIPs.Count -gt 0) {
        # Create output file
        $output = "Available_IP`r`n"
        foreach ($ip in $availableIPs) {
            $output += "$ip`r`n"
        }
        
        # Write to file
        [System.IO.File]::WriteAllText($outputFile, $output, [System.Text.Encoding]::UTF8)
        Write-Host "Saved to: $outputFile"
    }
    
} catch {
    Write-Host "Error: $($_.Exception.Message)"
    # Clean up Excel if needed
    try {
        if ($excel -ne $null) {
            $excel.Quit()
            [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel) | Out-Null
        }
    } catch {}
}